import Vue from 'vue'
import VueRouter from 'vue-router'
import { Store } from "vuex"
import store from '@/store'
import to from "await-to-js"
const Home = () => import('@/views/home/index.vue')
const Article = () => import('@/views/article/index.vue')
const Question = () => import('@/views/question/index.vue')
const User = () => import('@/views/user/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const Chat = () => import('@/views/user/chat.vue')
const Video = () => import('@/views/video/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')
const Login = () => import('@/views/login/index.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    components: {
      default: Home,
      bottom: Tabbar
    }
  },
  {
    path: '/article/:id',
    name: 'article',
    component: Article
  },
  {
    path: '/login',
    component: Login,
    meta: {}
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    },
    meta: {
      needLogin: true // 需要登录才能访问
    }
  },
  {
    path: '/user/profile',
    component: Profile,
    meta: {
      needLogin: true // 需要登录才能访问
    }
  },
  {
    path: '/user/chat',
    component: Chat,
    meta: {
      needLogin: true // 需要登录才能访问
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabbar
    }
  }
]

const router = new VueRouter({
  routes
})

const whitePath = ['/user', '/user/profile', '/user/chat']

router.beforeEach((to, from, next) => {
  // 登录已登录
  if(store.getters['user/getToken']){
    if (to.path.toLowerCase() === '/login'){
      next('/')
    }
    else{
      next()
    }
  }
  // 用户未登录
  else {
    // if (to.path.toLowerCase().startsWith('/user')){ 普通写法
    // if (whitePath.includes(to.path.toLowerCase())){ 白名单写法
    if (to.meta.needLogin){
      // 查询参数： redirect='/user/profile'
      next('/login?redirect=' + to.fullPath)
    }
    else{
      next()
    }
  }
})

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function pash(location){
  return routerPush.call(this, location).catch(error => error)
}

export default router
